<?php
/**
 * 奖品每天库存
 */
class Lotteryprize extends CS_Controller
{
    public function _init()
    {
        $this->load->helper('common');
        $this->load->library('pagination');
        $this->load->model('activity_lottery_model', 'activity_lottery');
        $this->load->model('lottery_prize_model', 'lottery_prize');
        $this->load->model('prize_every_day_model', 'prize_every_day');
        $this->load->model('user_model', 'user');
    }

    /**
     * 奖品列表
     */
    public function prizeList($pg = 1)
    {
        $getData = $this->input->get();
        $lottery = $this->lotteryExists($this->input->get('lottery_id'));
        if ($lottery === FALSE) {
            $this->error('lottery/index', '', '活动不存在');
        }
        $getData['uid'] = $this->uid; 
        $page_num = 15;
        $num = ($pg-1)*$page_num;
        $config['first_url'] = base_url('lotteryprize/index').$this->pageGetParam($this->input->get());
        $config['suffix'] = $this->pageGetParam($this->input->get());
        $config['base_url'] = base_url('lotteryprize/index');
        $config['total_rows'] = $this->lottery_prize->prizeTotal($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['page_list'] = $this->lottery_prize->prizeList($page_num, $num, $getData);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['lottery'] = $lottery;
        $data['prizeType'] = array(1 => '实物', 2 => '虚拟物品', 3 => '着想金币', 4 => '现场颁奖');
        $this->load->view('lotteryprize/list', $data);
    }

    /**
     * 添加奖品
     */
    public function addPrize()
    {
        $lottery = $this->lotteryExists($this->input->get('lottery_id'));
        if ($lottery === FALSE) {
            $this->error('lotteryprize/prizeList', '', '奖品不存在');
        }
        $this->load->view('lotteryprize/addPrize');
    }

    /**
     * 编辑奖品
     */
    public function editPrize($id)
    {
        $result = $this->prizeExists($id);
        if ($result === FALSE) {
            $this->error('lotteryprize/prizeList', '', '奖品不存在');
        }
        $data['prize'] = $result;
        $this->load->view('lotteryprize/editPrize', $data);
    }

     /**
     * 验证抽奖活动是否存在
     */
    private function lotteryExists($lotteryId)
    {
        if ( !$lotteryId) {
            return FALSE;
        }
        $result = $this->activity_lottery->findByLotteryId($lotteryId, $this->uid);
        if ($result->num_rows() == 0) {
            return FALSE;
        }
        return $result->row();
    }

      /**
     * 验证奖品是否存在
     */
    private function prizeExists($prizeId)
    {
        if ( !$prizeId) {
            return FALSE;
        }
        $result = $this->lottery_prize->findOnePrize($prizeId, $this->uid);
        if ($result->num_rows() == 0) {
            return FALSE;
        }
        return $result->row();
    }

    /**
     * 删除奖品 -- 假装删除了
     */
    public function deletePrize($id)
    {
        if ( !$id) {
            $this->error('lotteryprize/prizeList', '', '奖品不存在');
        }
        $result = $this->lottery_prize->deletePrize($id, $this->uid);
        if ( !$result) {
            $this->error('lotteryprize/prizeList', '', '数据异常');
        }
        $this->setActivityPrizeCache($id); //设置缓存

        $this->success('lotteryprize/prizeList', array('lottery_id'=> $this->input->get('lottery_id')), '删除成功');
    }

    /**
     * 奖品添加 编辑
     */
    public function prizePost()
    {
        $postData = $this->input->post();
        $url = isset($postData['prize_id']) ? 'lotteryprize/editPrize/'.$postData['prize_id'] : 'lotteryprize/addPrize';
        if ( !isset($postData['prize_name']) || mb_strlen($postData['prize_name']) > 60)  {
            $this->error($url, array('lottery_id'=>$postData['lottery_id']), '请输入奖品名称');
        }

        if ( empty($postData['grade'])) {
            $this->error($url, array('lottery_id'=>$postData['lottery_id']), '请选择奖品等级');
        }

        if ( empty($postData['status'])) {
            $this->error($url, array('lottery_id'=>$postData['lottery_id']), '请选择上下架状态');
        }

        if ( empty($postData['type'])) {
            $this->error($url, array('lottery_id'=>$postData['lottery_id']), '请选择奖品类型');
        }

        if ( !isset($postData['effective_days']) || $postData['effective_days'] < 0|| $postData['effective_days'] >= 100) {
            $this->error($url, array('lottery_id'=>$postData['lottery_id']), '请输入有效天数，有效天数为1-99天');
        }

        if ( !empty($postData['links']) && !checkBzUrl($postData['links'])) {
            $this->error($url, array('lottery_id'=>$postData['lottery_id']), '链接地址格式有误');
        }
        $imageData = '';
        if(!empty($_FILES['image']['name'])){
            if (empty($postData['oldfilename'])) {
                $imageData = $this->dealWithImages('image', '', 'lotteryPrize');
            } else {
                $imageData = $this->dealWithImages('image', $postData['oldfilename'], 'lotteryPrize');
            }
            if ($imageData == false) {
                $this->error($url, array('lottery_id'=>$postData['lottery_id']), '图片上传失败！');
            }
            $ifResize = $this->dealWithImagesResize($imageData, 188, 165);
            if ($ifResize == false) {
                $this->error($url, array('lottery_id'=>$postData['lottery_id']), '缩略图生成失败！');
            }
        } else {
            if (empty($postData['oldfilename'])) {
                $this->error($url, array('lottery_id'=>$postData['lottery_id']), '请上传图片');
            } else {
                $imageData['file_name'] = $postData['oldfilename'];
            }
        }

        $flag = FALSE;
        if (isset($postData['prize_id'])) {
            if ( !$postData['prize_id']) {
                $this->error($url, array('lottery_id'=>$postData['lottery_id']), '数据异常');
            }
            $flag = $this->lottery_prize->updatePrize($postData, $imageData);

            $this->setActivityPrizeCache($postData['lottery_id']); //设置缓存
        } else {
            $flag = $this->lottery_prize->insertPrize($postData, $imageData);
        }
        if ($flag) {
            $this->success('lotteryprize/prizeList', array('lottery_id'=> $postData['lottery_id']), '操作成功');
        } else {
            $this->error($url, array('lottery_id'=>$postData['lottery_id']), '数据异常');
        }
    }

    /**
     * 奖品每日价格
     */
    public function dailyPrize()
    {
        $prizeId = $this->input->get('prize_id');
        if ( empty($prizeId)){
            $this->error('lottery/index', '', '奖品编号不存在');
        }
        $result = $this->lottery_prize->findOnePrize($prizeId, $this->uid);
        if ($result->num_rows() == 0) {
            $this->error('lottery/index', '', '奖品编号不存在');
        }
        $prize = $result->row();
        $year  = $this->input->get('year') ? $this->input->get('year') : date('Y');
        $month = $this->input->get('month') ? $this->input->get('month') : date('m');
        $prefs = array (
            'template' => $this->calendarTemplate($year, $month)
            // 'show_next_prev' => true,
            // 'next_prev_url' => base_url('lottery/dailyPrize?lottery_id='. $this->input->get('lottery_id'). '&prize_id='. $prizeId),

        );
        $this->load->library('calendar',$prefs);
        $generate = $this->getCalendarData($year, $month, $prize);
        $data['generate'] = $this->calendar->generate($year, $month, $generate);
        $data['prize'] = $prize;
        $this->load->view('lotteryprize/dailyPrize', $data);
    }

    /**
     * 日历模板
     */
    private function calendarTemplate($year, $month)
    {
        $url = base_url('lotteryprize/dailyPrize?lottery_id='. $this->input->get('lottery_id'). '&prize_id='. $this->input->get('prize_id'));

        $prveUrl = $url. '&'. http_build_query($this->adjust_date($month - 1, $year));
        $nextUrl = $url. '&'. http_build_query($this->adjust_date($month + 1, $year));
        return  array (
                        'table_open'                => '<p class="dailyPrize-header">'.$year .'-'. $month. '</p>
                                                            <div class="dailyPrize-inner">
                                                              <div class="carousel">
                                                                <table class="table">',
                        'heading_row_start'         => '',
                        'heading_previous_cell'     => '',
                        'heading_title_cell'        => '',
                        'heading_next_cell'         => '',
                        'heading_row_end'           => '',
                        'week_row_start'            => '<tr>',
                        'week_day_cell'             => '<th>{week_day}</th>',
                        'week_row_end'              => '</tr>',
                        'cal_row_start'             => '<tr>',
                        'cal_cell_start'            => '<td class="other-month prev-month">',
                        'cal_cell_start_today'      => '<td class="other-month prev-month">',
                        'cal_cell_start_nexttoday'  => '<td class="this-month">',
                        'cal_cell_content'          => '<a href="{content}">{day}</a>',
                        'cal_cell_content_today'    => '<a href="{content}"><strong>{day}</strong></a>',
                        'cal_cell_no_content'       => '{day}',
                        'cal_cell_no_content_today' => '<strong>{day}</strong>',
                        'cal_cell_blank'            => '<div class="info"></div>',
                        'cal_cell_end'              => '</td>',
                        'cal_cell_end_today'        => '</td>',
                        'cal_row_end'               => '</tr>',
                        'table_close'               => '</table></div>
                        <a class="left carousel-control" href="'.$prveUrl.'" role="button" data-slide="prev">
                            <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
                            <span class="sr-only">Previous</span>
                        </a>
                        <a class="right carousel-control" href="'.$nextUrl.'" role="button" data-slide="next">
                            <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
                            <span class="sr-only">Next</span>
                        </a>
                    </div>'
                    );
    }

    /**
     * 获取年月的参数
     */
    private function adjust_date($month, $year)
    {
        $date = array();
        $date['month']  = $month;
        $date['year']   = $year;

        while ($date['month'] > 12) {
            $date['month'] -= 12;
            $date['year']++;
        }

        while ($date['month'] <= 0) {
            $date['month'] += 12;
            $date['year']--;
        }

        if (strlen($date['month']) == 1) {
            $date['month'] = '0'.$date['month'];
        }
        return $date;
    }

    /**
     * 日历
     */
    public function getCalendarData($year, $month, $prize){
        $status = array(1 => '可抽奖', 2 => '不可抽奖');
        $getData = $this->input->get();
        $getData['date'] = $year.'-'.$month;
        $getData['prize_id'] = $prize->prize_id;
        $result = $this->prize_every_day->find($getData);
        //$dayNum = cal_days_in_month(CAL_GREGORIAN, $month, $year); 由于服务不支持该函数  so
        $dayNum = $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
        $generate = array();
        if ($result->num_rows() > 0){
            $prizeDay = $result->result();
            for($i=1;$i<=$dayNum;$i++){
                $day = $i;
                if (strlen($i) == 1){
                    $day = '0'.$i;
                }
                $date = $year.'-'.$month.'-'.$day;
                $flag = true;
                foreach ($prizeDay as $key=>$value) {
                    if ($i == $value->day) {
                        $flag = false;
                        $status = ($value->status ==2) ? '不可抽奖' : '可抽奖';
                        $probability = ($value->probability <= 0) ? '--' : $value->probability.'%';
                        $generate[$i] = '<div class="info"><div class="day-date">'.$i.'</div>';
                        $generate[$i] .= '<div class="day-content">
                                            <div>
                                                <p>数量：'. $value->quantity.'   剩余：' .$value->surplus_quantity. '</p>
                                                <p>中奖概率：'. $probability. '</p>
                                                <p>状态：'. $status.'</p>
                                            </div></div></div>';
                        // $generate[$i] .='<div class="info info2" >
                        //         <div class="day-date2">'.$i.'</div>
                        //         <div class="day-content">
                        //             <div>
                        //                 <p>数量：'. $value->quantity.'</p>
                        //                 <p>剩余：'. $value->surplus_quantity.'</p>
                        //                 <p>状态：'. $value->probability.'</p>
                        //                 <p>中奖概率：'. $probability.' </p>
                        //                 <p>指定中奖者：'. $winnersUser.'</p>
                        //                 <p>中奖时间段：'. $value->start_time. '--'. $value->end_time.'</p>
                        //             </div></div></div>';
                        unset($prizeDay[$key]);
                        break;
                    }
                }
                if ($flag){
                    $generate[$i] = '<div class="info">
                                    <div class="day-date">'. $i.'</div>
                                    <div class="day-content">
                                        <div>
                                            <p>数量：--</p>
                                            <p>剩余：--</p>
                                            <p>状态：--</p>
                                        </div>
                                    </div>
                                </div>';
                }
            }
        } else {
            for($i=1;$i<=$dayNum;$i++){
                $day = $i;
                if (strlen($i) == 1){
                    $day = '0'.$i;
                }
                $date = $year.'-'.$month.'-'.$day;
                $generate[$i] = '<div class="info">
                                    <div class="day-date">'. $i.'</div>
                                    <div class="day-content">
                                        <div>
                                            <p>数量：--</p>
                                            <p>剩余：--</p>
                                            <p>状态：--</p>
                                        </div>
                                    </div>
                                </div>';
            }
        }
        return $generate;
    }

    /**
     *  每日奖品库存 提交
     */
    public function dailyPrizePost()
    {
        $postData = $this->dailyPrizeValidate();

        $this->db->trans_start();
        $updateData = array();
        $result = $this->prize_every_day->find(array('date' => $postData['date'], 'prize_id'=> $postData['prize_id']));
        $date = array_flip($postData['date']);
        if ($result->num_rows() > 0) {
            foreach ($result->result() as $key=>$value) {
                if (array_key_exists($value->date, $date)) {
                    $updateData[$key]['date'] = $value->date;
                    $updateData[$key]['day_id'] = $value->day_id;
                    unset($date[$value->date]);
                }
            }
            if ( !empty($updateData)) {
                $this->prize_every_day->updateBatch($updateData, $postData);
            }
        }
        if ( !empty($date)) {
            $insertId = $this->prize_every_day->insertBatch($postData, $date);
        }
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            $this->ajaxJson(false, '内部操作失败');
        } else {
            $this->setActivityPrizeCache($postData['lottery_id']); //设置缓存
            $this->ajaxJson(true, '');
        }
    }

      /**
     * 缓存今天的剩余数量
     */
    private function setActivityPrizeCache($lotteryId)
    {
        $activityPrize = $this->lottery_prize->findPrizes(['lottery_id' => $lotteryId]);
        if ($activityPrize->num_rows() == 0) {
            $this->cache->memcached->delete('activityPrize'. $lotteryId); //删除缓存
        }
        $activityPrize = $activityPrize->result();
        $expires = strtotime(date('Y-m-d 23:59:59')) - time();
        $this->cache->memcached->save('activityPrize'. $lotteryId, $activityPrize, $expires); //缓存今天
    }

    /**
     * 效验
     */
    public function dailyPrizeValidate()
    {
        $postData = $this->input->post();
        if (empty($postData['prize_id'])){
            $this->ajaxJson(false, '奖品编号不存在');
        }

        $result = $this->lottery_prize->findOnePrize($postData['prize_id'], $this->uid);
        if ($result->num_rows() == 0) {
            $this->ajaxJson(false, '奖品不存在');
        }
        $postData['lottery_id'] = $result->row()->lottery_id;

        if (empty($postData['date'])){
            $this->ajaxJson(false, '日期不可为空，刷新一下！');
        }
        $date = array_map('valiDate', explode(',', trim($postData['date'], ',')));
        if (in_array(false, $date)) {
            $this->ajaxJson(false, '日期格式不正确，刷新一下！');
        }
        $postData['date'] = $date;

        if (!is_numeric($postData['quantity']) || $postData['quantity'] < 0 || $postData['quantity'] >= 16777215) {
            $this->ajaxJson(false, '数量只能为正整数，不可超出范围');
        }
        if ( !empty($postData['probability']) && ( !is_numeric($postData['probability']) || $postData['probability'] < 0 || $postData['probability'] > 100)) {
            $this->ajaxJson(false, '概率只能为正整数，范围1-100');
        }

        return $postData;
    }
}